<template>
  <div class="messageDetail">
    <el-dialog
      title="消息详情"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :show-close="true"
      :close-on-press-escape="false"
    >
      <el-form
        :model="sendmessage"
        :rules="rules"
        label-position="right"
        label-width="100px"
        ref="form"
      >
        <el-form-item label="消息名称" prop="title">
          <el-input v-model="sendmessage.title"></el-input>
        </el-form-item>
        <el-form-item label="短信模板" prop="smsTemplateId">
          <el-select @change="changeTemplate" v-model="sendmessage.smsTemplateId" placeholder="请选择">
            <el-option
              v-for="item in smsTemplateList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发送内容" prop="content2">
          <el-row class="message">
            <el-col :sm="12" :xs="24" style="margin-top: 10px;">
              <el-form-item
                :key="index"
                :label="key"
                prop="content"
                v-for="(item, key, index) in templateParam"
              >
                <el-input
                  :value="item"
                  @input="(value)=>{templateCode(value,key,index)}"
                  maxlength="255"
                />
              </el-form-item>
            </el-col>
            <el-col :sm="12" :xs="24" style="margin-top: 10px;">
              <el-form-item label="预览：">
                <div class="article" v-html="content" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="发送的类型" prop="type">
          <el-select @change="changeType" v-model="sendmessage.type" placeholder="请选择">
            <el-option v-for="item in types" :key="item.key" :label="item.label" :value="item.key"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="sendmessage.type==1 || sendmessage.type==2"
          label="子发送类型"
          prop="specificType"
        >
          <el-select
            @change="changeSpecificType"
            v-model="sendmessage.specificType"
            placeholder="请选择"
          >
            <el-option
              v-for="item in specificTypes"
              :key="item.key"
              :label="item.label"
              :value="item.key"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="sendmessage.type==2"
          :label="specificTypeLabel"
          prop="specificTypeValue"
        >
          <el-select
            multiple
            filterable
            remote
            :remote-method="remoteMethod"
            :loading="loading"
            v-model="sendmessage.receiverValue"
            placeholder="请输入关键词"
          >
            <el-option
              v-for="item in specificTypeValues"
              :key="item.key"
              :label="item.label"
              :value="item.key"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="sendmessage.type==3" label="选择客户" prop="selectCustomer">
          <el-select
            multiple
            filterable
            remote
            :remote-method="remoteSelectCustomerMethod"
            :loading="loading"
            v-model="sendmessage.receiverValue"
            placeholder="请输入关键词"
          >
            <el-option
              v-for="item in selectCustomerList"
              :key="item.key"
              :label="item.label"
              :value="item.key"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="sendmessage.type==4" label="输入手机号" prop="selectPhone">
          <el-select
            multiple
            filterable
            allow-create
            v-model="sendmessage.receiverValue"
            placeholder="请输入手机号"
          >
            <el-option
              v-for="item in phoneList"
              :key="item.key"
              :label="item.label"
              :value="item.key"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发送时间" prop="sendTime">
          <el-date-picker
            v-model="sendmessage.sendTime"
            type="datetime"
            value-format="yyyy-MM-dd hh:mm:ss"
            placeholder="选择日期时间"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmClick">确 定</el-button>
        <el-button @click="cancelClick">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { get, postJson, postXform } from "@/utils/request.js";

export default {
  // id即编辑的id，visible属性用来监听是否显示弹窗
  props: ["visible"],
  components: {},
  watch: {},
  computed: {
    dialogVisible: {
      get() {
        return this.visible;
      },
      set(value) {
        this.$emit("update:visible", value);
      }
    },
    specificTypes: {
      get() {
        if (this.sendmessage.type == 1) {
          return this.specificTypes1;
        } else if (this.sendmessage.type == 2) {
          return this.specificTypes2;
        }
      }
    },
    specificTypeLabel: {
      get() {
        if (this.sendmessage.specificType == 5) {
          this.specificTypeUrl = "sendMessage/checkActivity";
          return "筛查活动";
        } else if (this.sendmessage.specificType == 6) {
          this.specificTypeLabel = "门店";
          return "sendMessage/store";
        } else if (this.sendmessage.specificType == 7) {
          this.specificTypeUrl = "sendMessage/doctor";
          return "医生";
        } else if (this.sendmessage.specificType == 8) {
          this.specificTypeUrl = "sendMessage/distribute";
          return "分销商";
        } else if (this.sendmessage.specificType == 9) {
          this.specificTypeUrl = "sendMessage/customer";
          return "客户";
        }
      }
    }
  },
  data() {
    return {
      sendmessage: {
        id: null,
        title: null,
        message: null,
        smsTemplateId: null,
        templateParams: null,
        type: null,
        specificType: null,
        receiverValue: [],
        sendTime: null
      },
      smsTemplateList: [],
      smsTemplate: null,
      content: "",
      templateParam: [],
      // 表单校验
      rules: {},
      statuss: [
        { key: 0, label: "未执行" },
        { key: 1, label: "已执行" },
        { key: 2, label: "执行失败" }
      ],
      types: [
        { key: 1, label: "按客户类型发送" },
        { key: 2, label: "按客户来源发送" },
        { key: 3, label: "主动选择客户" },
        { key: 4, label: "输入手机号" },
        { key: 5, label: "最近三月无消费" },
        { key: 6, label: "最近三月有消费" },
      ],
      //   specificTypes: [],
      specificTypes1: [
        { key: 1, label: "客户" },
        { key: 2, label: "医生" },
        { key: 3, label: "员工" },
        { key: 4, label: "分销商" }
      ],
      specificTypes2: [
        { key: 5, label: "筛查活动" },
        { key: 6, label: "门店" },
        { key: 7, label: "医生" },
        { key: 8, label: "分销商" },
        { key: 9, label: "客户" },
        { key: 10, label: "其他" }
      ],

      specificTypeUrl: "",
      //   specificTypeLabel: "",
      loading: false,
      specificTypeValues: [],

      selectCustomerList: [],

      phoneList: []
    };
  },
  methods: {
    changeTemplate(id) {
      const vm = this;
      if (id) {
        for (const item of vm.smsTemplateList) {
          if (item.id === id) {
            let templateParam = {};
            if (typeof item.templateParams == "string") {
              let splits = item.templateParams.split(",");
              splits.forEach(e => {
                templateParam[e] = "";
              });
            } else {
              templateParam = item.templateParams;
            }
            for (const prop in templateParam) {
              templateParam[prop] = "";
            }
            if (vm.sendmessage.templateParams) {
              let temp=JSON.parse(vm.sendmessage.templateParams);
              for (const prop in temp) {
                templateParam[prop] = temp[prop];
              }
            }
            vm.smsTemplate = item;
            vm.templateParam = templateParam;
            this.content = item.content;
            break;
          }
        }
        vm.changeContent();
      }
    },
    templateCode(val, key) {
      const vm = this;
      vm.templateParam[key] = val;
      vm.changeContent();
    },
    changeContent() {
      const vm = this;
      if (!vm.smsTemplate) {
        return;
      }
      let content = vm.smsTemplate.content;

      for (const key in vm.templateParam) {
        let strs = "${" + key + "}";
        if (vm.templateParam[key]) {
          content = content.replace(strs, vm.templateParam[key]);
        }
      }
      vm.content = content;
    },
    changeType(key) {},
    changeSpecificType(key) {
      if (key) {
        this.receiverValue = [];
      }
    },
    remoteMethod(query) {
      if (query !== "") {
        this.loading = true;
        get(this.specificTypeUrl, { name: query }).then(res => {
          this.loading = false;
          this.specificTypeValues = res.data.data;
        });
      } else {
        this.specificTypeValues = [];
      }
    },
    remoteSelectCustomerMethod(query) {
      if (query !== "") {
        this.loading = true;
        get("sendMessage/customerAll", { name: query }).then(res => {
          this.loading = false;
          this.selectCustomerList = res.data.data;
        });
      } else {
        this.selectCustomerList = [];
      }
    },
    initEdit(row) {
      this.smsTemplate = null;
      this.content = "";
      this.templateParam = [];
      if (this.smsTemplateList.length == 0) {
        get("sendMessage/listSmsTemplate").then(res => {
          this.smsTemplateList = res.data.data;
          this.changeTemplate(this.sendmessage.smsTemplateId);
        });
      }
      if (row) {
        this.sendmessage = {
          id: row.id,
          title: row.title,
          message: row.message,
          smsTemplateId: row.smsTemplateId,
          templateParams: row.templateParams,
          type: row.type,
          specificType: row.specificType,
          sendTime: row.sendTime
        };
        if (row.type == 2) {
          if (row.specificType == 5) {
            get("sendMessage/getCheckActivity", {
              id: row.receiverValue
            }).then(res => {
              this.specificTypeValues = res.data.data;
            });
          } else if (row.specificType == 6) {
            get("sendMessage/getStore", { id: row.receiverValue }).then(res => {
              this.specificTypeValues = res.data.data;
            });
          }
          if (row.specificType == 7) {
            get("sendMessage/getDoctor", { id: row.receiverValue }).then(
              res => {
                this.specificTypeValues = res.data.data;
              }
            );
          }
          if (row.specificType == 8 || row.specificType == 9) {
            get("sendMessage/getCustomer", { id: row.receiverValue }).then(
              res => {
                this.specificTypeValues = res.data.data;
              }
            );
          }
        } else if (row.type == 3) {
          get("sendMessage/getCustomers", { ids: row.receiverValue }).then(
            res => {
              this.selectCustomerList = res.data.data;
            }
          );
        }
        this.sendmessage.receiverValue = [];
        if (row.receiverValue) {
          let temp = row.receiverValue.split(",");
          temp.forEach(t => {
            this.sendmessage.receiverValue.push(Number.parseInt(t));
          });
        }
        this.changeTemplate(this.sendmessage.smsTemplateId);
      } else {
        this.sendmessage = {
          id: null,
          title: null,
          message: null,
          smsTemplateId: null,
          templateParams: null,
          type: null,
          specificType: null,
          specificTypeValue: null,
          receiverValue: [],
          sendTime: null
        };
      }
    },
    // 确认保存
    confirmClick() {
      let param = { ...this.sendmessage };
      param.templateParams = JSON.stringify(this.templateParam);
      param.receiverValue = param.receiverValue.join(",");
      param.message=this.content;
      this.$refs.form.validate(valid => {
        if (valid) {
          let url = this.sendmessage.id
            ? "/sendMessage/update"
            : "/sendMessage/add";
          postXform(url, param).then(res => {
            this.$message({ message: "操作成功", type: "success" });
            this.dialogVisible = false;
            this.$emit("success");
          });
        } else {
          return false;
        }
      });
    },
    cancelClick() {
      this.dialogVisible = false;
    }
  },
  mounted() {},
  created() {}
};
</script>

<style lang="less">
</style>
